package com.atzexu.web.controller;

import com.atzexu.domain.KsClass;
import com.atzexu.domain.User;
import com.atzexu.domain.dto.UserDTO;
import com.atzexu.service.ClassService;
import com.atzexu.service.UserService;
import com.atzexu.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * 登录控制层
 */
@RestController
@RequestMapping("/v1/login")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private ClassService classService;

    /**
     * 根据用户名查询用户类型并回显班级列表数据
     *
     * @param mobile
     * @return
     */
    @GetMapping("/{mobile}")
    public R getUserTypeByMobile(@PathVariable String mobile) {
        R r = null;
        // 查询登录账号是否为老师账号
        User user = userService.getUserTypeByMobile(mobile);
        if (user.getRoleId() == 1) { // 说明是老师账号 查询班级列表全部数据
            List<KsClass> allList = classService.getClassList();
            r = new R(0, "操作成功", allList);
        } else if (user.getRoleId() == 2) { // 学生账号 查询学生所在的班级数据
            List<KsClass> studentList = classService.getStudetClass(user.getClassId());
            r = new R(0, "操作成功", studentList);
        }
        return r;
    }

    /**
     * 登录
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/in")
    public R login(@RequestBody UserDTO userDTO, HttpSession session) {
        // 每次登录之前先将session中的user先清除
        session.removeAttribute("user");
        // 前端传来的数据有问题 进行处理后封装到User中
        User user = new User();
        user.setMobile(userDTO.getName());
        user.setPassword(userDTO.getPassword());

        User userVo = userService.getUserByUserNameAndPassword(user);
        // 将前端传来的classId放入userVo中
        userVo.setClassId(Integer.valueOf(userDTO.getClassId()));
        R r = null;
        if (userVo != null) {
            r = new R(0, "操作成功", null);
            session.setAttribute("user", userVo);
        } else {
            r = new R(0, "操作失败", null);
        }
        return r;
    }

}
